<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Edit, Delete, Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

interface Advertisement {
  id: string
  title: string
  description?: string
  imageUrl: string
  linkUrl?: string
  sortOrder: number
  isActive: boolean
  startDate?: string
  endDate?: string
  clickCount: number
  createdAt: string
  updatedAt: string
}

const advertisementList = ref<Advertisement[]>([])
const advertisementForm = reactive({
  title: '',
  description: '',
  imageUrl: '',
  linkUrl: '',
  sortOrder: 0,
  isActive: true,
  startDate: '',
  endDate: ''
})
const advertisementDialog = ref(false)
const editingId = ref<string | null>(null)
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

async function fetchAdvertisements() {
  loading.value = true
  try {
    const { data } = await request.get('/api/admin/advertisements', {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    advertisementList.value = data.advertisements
    total.value = data.total
  } catch (error) {
    ElMessage.error('광고 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

function resetForm() {
  advertisementForm.title = ''
  advertisementForm.description = ''
  advertisementForm.imageUrl = ''
  advertisementForm.linkUrl = ''
  advertisementForm.sortOrder = 0
  advertisementForm.isActive = true
  advertisementForm.startDate = ''
  advertisementForm.endDate = ''
  editingId.value = null
}

function openCreateDialog() {
  resetForm()
  advertisementDialog.value = true
}

function openEditDialog(row: Advertisement) {
  advertisementForm.title = row.title
  advertisementForm.description = row.description || ''
  advertisementForm.imageUrl = row.imageUrl
  advertisementForm.linkUrl = row.linkUrl || ''
  advertisementForm.sortOrder = row.sortOrder
  advertisementForm.isActive = row.isActive
  advertisementForm.startDate = row.startDate ? row.startDate.split('T')[0] : ''
  advertisementForm.endDate = row.endDate ? row.endDate.split('T')[0] : ''
  editingId.value = row.id
  advertisementDialog.value = true
}

async function saveAdvertisement() {
  if (!advertisementForm.title || !advertisementForm.imageUrl) {
    ElMessage.error('제목과 이미지 URL을 입력하세요')
    return
  }

  try {
    const formData = {
      ...advertisementForm,
      startDate: advertisementForm.startDate || null,
      endDate: advertisementForm.endDate || null
    }

    if (editingId.value) {
      // 편집
      await request.put(`/api/admin/advertisements/${editingId.value}`, formData)
      ElMessage.success('업데이트 성공')
    } else {
      // 신규 추가
      await request.post('/api/admin/advertisements', formData)
      ElMessage.success('생성 성공')
    }
    advertisementDialog.value = false
    await fetchAdvertisements()
  } catch (error) {
    ElMessage.error(editingId.value ? '업데이트 실패' : '생성 실패')
  }
}

async function deleteAdvertisement(row: Advertisement) {
  try {
    await ElMessageBox.confirm(
      `"${row.title}" 광고를 삭제하시겠습니까?`,
      '삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    await request.delete(`/api/admin/advertisements/${row.id}`)
    ElMessage.success('삭제 성공')
    await fetchAdvertisements()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 실패')
    }
  }
}

// 图片上传成功处理
function handleImageSuccess(response: any) {
  advertisementForm.imageUrl = response.coverUrl
  ElMessage.success('이미지 업로드 성공')
}

// 获取图片URL
function getImageUrl(url: string) {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `${API_BASE_URL}${url}`
}

// 分页处理
function handlePageChange(page: number) {
  currentPage.value = page
  fetchAdvertisements()
}

function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
  fetchAdvertisements()
}

onMounted(() => {
  fetchAdvertisements()
})
</script>

<template>
  <div class="advertisement-management">
    <div class="header">
      <h1>광고 관리</h1>
      <div class="actions">
        <el-button type="primary" :icon="Plus" @click="openCreateDialog">
          광고 추가
        </el-button>
        <el-button :icon="Refresh" @click="fetchAdvertisements">
          새로고침
        </el-button>
      </div>
    </div>

    <el-table :data="advertisementList" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="이미지" width="120">
        <template #default="{ row }">
          <img
            v-if="row.imageUrl"
            :src="getImageUrl(row.imageUrl)"
            :alt="row.title"
            style="width: 80px; height: 45px; object-fit: cover; border-radius: 4px;"
          />
          <span v-else class="no-image">이미지 없음</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="제목" min-width="200" />
      <el-table-column prop="description" label="설명" min-width="200" show-overflow-tooltip />
      <el-table-column prop="linkUrl" label="링크 URL" min-width="200" show-overflow-tooltip />
      <el-table-column prop="sortOrder" label="정렬 순서" width="100" />
      <el-table-column prop="isActive" label="활성화" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'info'">
            {{ row.isActive ? '활성' : '비활성' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="clickCount" label="클릭 수" width="100" />
      <el-table-column label="시작일" width="120">
        <template #default="{ row }">
          {{ row.startDate ? new Date(row.startDate).toLocaleDateString() : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="종료일" width="120">
        <template #default="{ row }">
          {{ row.endDate ? new Date(row.endDate).toLocaleDateString() : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="작업" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" :icon="Edit" @click="openEditDialog(row)">
            편집
          </el-button>
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="deleteAdvertisement(row)"
          >
            삭제
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="advertisementDialog"
      :title="editingId ? '광고 편집' : '광고 추가'"
      width="600px"
    >
      <el-form :model="advertisementForm" label-width="100px">
        <el-form-item label="제목" required>
          <el-input v-model="advertisementForm.title" />
        </el-form-item>
        <el-form-item label="설명">
          <el-input v-model="advertisementForm.description" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="이미지" required>
          <div style="display: flex; gap: 12px; align-items: center; width: 100%">
            <el-upload
              :action="`${API_BASE_URL}/api/admin/uploads/cover`"
              name="cover-upload"
              :with-credentials="true"
              :show-file-list="false"
              :on-success="handleImageSuccess"
            >
              <img
                v-if="advertisementForm.imageUrl"
                :src="getImageUrl(advertisementForm.imageUrl)"
                style="width: 120px; height: 68px; object-fit: cover; border-radius: 6px;"
                alt="광고 이미지"
              />
              <el-button v-else type="primary" :icon="Picture">이미지 업로드</el-button>
            </el-upload>
            <el-input
              v-model="advertisementForm.imageUrl"
              placeholder="또는 이미지 URL을 직접 입력"
              style="flex: 1"
            />
          </div>
        </el-form-item>
        <el-form-item label="링크 URL">
          <el-input v-model="advertisementForm.linkUrl" placeholder="클릭 시 이동할 URL (선택사항)" />
        </el-form-item>
        <el-form-item label="정렬 순서">
          <el-input-number v-model="advertisementForm.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="시작일">
          <el-date-picker
            v-model="advertisementForm.startDate"
            type="date"
            placeholder="시작일 선택 (선택사항)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="종료일">
          <el-date-picker
            v-model="advertisementForm.endDate"
            type="date"
            placeholder="종료일 선택 (선택사항)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="활성화">
          <el-switch v-model="advertisementForm.isActive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="advertisementDialog = false">취소</el-button>
          <el-button type="primary" @click="saveAdvertisement">
            {{ editingId ? '업데이트' : '생성' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.advertisement-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.actions {
  display: flex;
  gap: 12px;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
